package com.opgea.crm.repository.security;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.opgea.crm.domain.entities.security.CrmUser;

@Repository(value="UserRepository")
public class CrmUserRepositoryImpl implements CrmUserRepository{

	@PersistenceContext
	EntityManager em;
	
	 
	@Override
	public CrmUser findByLoginId(String userName) {
		
		return (CrmUser) em.createQuery("SELECT c FROM CrmUser c WHERE c.userName = :userName")
		.setParameter("userName", userName).getSingleResult();
	}


	@Override
	@Transactional
	public void create(CrmUser user) {
		em.persist(user);
	}
	
	@Override
	@Transactional
	public void update(CrmUser user) {
		if (em.find(CrmUser.class, user.getUserName()) == null) {
	        throw new IllegalArgumentException("Unknown CrmUser id: " + user.getUserName());
	      }
		CrmUser managedUser = em.merge(user);	
	}


	@Override
	public CrmUser findByEmpId(Long empId) {
		CrmUser user = (CrmUser) em.createQuery("SELECT c FROM CrmUser c WHERE c.employee.id = :empId")
		.setParameter("empId", empId).getSingleResult();
		System.out.println("User Impl : "+user);
		return user;
	}

}
